﻿var isRequest = false;
var Util = {
    template  : function(text, data){
        var render;
        var noMatch = /(.)^/;
        var escapes = {
            "'" : "'",
            '\\' : '\\',
            '\r' : 'r',
            '\n' : 'n',
            '\t' : 't',
            '\u2028' : 'u2028',
            '\u2029' : 'u2029'
        };
        
        var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
        var settings = {
            evaluate : /<@([\s\S]+?)@>/g,
            interpolate : /<@=([\s\S]+?)@>/g,
            escape : /<@-([\s\S]+?)@>/g
        };
        
        var matcher = new RegExp([(settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source].join('|') + '|$', 'g');
        
        var index = 0;
        var source = "__p+='";
        text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
            source += text.slice(index, offset).replace(escaper, function(match) {
                return '\\' + escapes[match];
            });
            if(escape) {
                source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
            }
            if(interpolate) {
                source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
            }
            if(evaluate) {
                source += "';\n" + evaluate + "\n__p+='";
            }
            index = offset + match.length;
            return match;
        });
        source += "';\n";
        
        if(!settings.variable)
        source = 'with(obj||{}){\n' + source + '}\n';
        source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + "return __p;\n";
        
        try {
            render = new Function(settings.variable || 'obj', source);
            } catch (e) {
            e.source = source;
            throw e;
        }
        
        if(data)
        return render(data);
        var template = function(data) {
            return render.call(this, data);
        };
        
        template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
        
        return template;
    },
    event:function(events){
        var me = this,
            reg = /[^\s]+/g,
            matchs;

        $.each(events, function(k, v){
            matchs = k.match(reg);
            matchs.length == 2 ? 
            $(matchs[0]).bind(matchs[1], function(e){
                me[v].apply(me, [this, e]);
            }) :
            $(matchs[0]).delegate(matchs[1], matchs[2], function(e){
                me[v].apply(me, [this, e]);
            });
        });
    },
    tips : function(text){
        var $tips = $(".com-tips"),
            tipsW = $tips.width(),
            tipsMargin = ($(window).width() - tipsW)/2;
        $tips.html(text);
        $tips.css("left",tipsMargin);
        $tips.animate({"top":0},1000,function(){
            setTimeout(function(){
                $tips.animate({"top":"-24px"},1000);
            },1000);
        });
    },
    /***
     * 将任意数量对象或者字符串传入该方法，若有任意一个为空，则返回true
     * 可判断 空对象 空数组 空字符串 undefined null
     * @returns {boolean}
     */
    isEmpty: function (){
        var len = arguments.length;

        var getType = Object.prototype.toString;

        if(len==0){ return true; }
        for(var i=0;i<len;i++){
            var a = arguments[i];
            if(typeof a === "undefined" || a == null || (typeof a === "string" && a.trim() == "")){
                return true;
            }else if(typeof a === "object"){
                var flg = true;
                for (var name in a ) {
                    flg=false;
                    break;
                }
                if(flg){ return true; }
            }
        }
        return false;
    },
    isInteger:function (obj) {
        return typeof obj === 'number' && obj%1 === 0
    },
    ajaxRequest : function(option){
        var set_option = {
            dataType:'json',
            showLoading : true,
            type: "get",
            beforeSend:function() {
                if(!isRequest) {
                    isRequest = true;
                    if (set_option.showLoading != false) {
                        $(".mask-loading").show();
                        if($(".pop-box").length>0){
                            $(".mask-loading").css({"height":"100%","top":"0"});
                        }
                    }
                }
            },
            timeout: 999999
        };
        $.extend(set_option,option);
        return $.ajax(set_option).done(function(json){
            if(json.code == 406){
                pop.alert(json.message,function(){
                    location.assign('login.html');
                });
            }else if(json.code == 401){
                pop.alert("页面已过时",function () {
                    location.assign('login.html');
                })
            }else if(json.code != 200){
                if(set_option.autoError!=false){
                    pop.alert(json.message);
                }
            }
            //$(".mask-loading").hide();
            $.isFunction(option.done)?option.done(json):"";
        }).complete(function(XMLHttpRequest,status){
            if(status=='timeout'){//超时,status还有success,error等值的情况
                pop.alert("请求超时，请稍后再试！");
            }
            isRequest = false;
            $(".mask-loading").hide();
        });
    },
    getData : function(ele){
        var obj = {};
        $(ele).find(".ht-data").each(function(){
            var attr = $(this).attr("id"),val="";
            if(attr == ""){console.error("ht-data attr name is null;")}
            val = $(this).val();
            obj[attr] = val;
        });
        return obj;
    },
    /***
     * 格式化记录方法，传入数字类型的记录数，格式化成中文格式，可以传入单位或者不传
     * @param num
     * @param unit
     * @returns {*}
     */
    formatRecord:function(num,unit){
        var level = num.toString().length/4;
        var sNum = num.toString();
        var arr,result;
        var _unit = Util.isEmpty(unit)?"":" "+unit;
        if(level > 0 && level <= 1){
            result=num+_unit;
        }else if(level>1 && level <= 2){
            result = sNum.substr(0,sNum.length-4)+" 万 "+ parseInt(sNum.substr(sNum.length-4)) + _unit;
        }else if(level>2 && level <= 3){
            result = sNum.substr(0,sNum.length-8)+" 亿 " + parseInt(sNum.substr(sNum.length-8,sNum.length-5)) + " 万 " + _unit;
        }else{
            arr = (num/100000000).toString().split(".")[0];
            result=arr+" 亿" + _unit;
        }
        return result;
    },
    nanoNum:function(num){//999 1000亿2345万6789
        var sNum = num.toString();
        var finalNum,len = sNum.length;
        if(len<=3){
            finalNum = num
        }else if(len == 4){
            finalNum = sNum.substr(0,1) + "千+";
        }else if(len > 4 && len < 8){
            finalNum = sNum.substr(0,len-4) + "万+";
        }else if(len == 8){
            finalNum = sNum.substr(0,1) + "千万+";
        }else if(len > 8 && len < 12){
            finalNum = sNum.substr(0,len-8) + "亿+";
        }else if(len == 12){
            finalNum = sNum.substr(0,1) + "千亿+";
        }else if(len > 12){
            finalNum = "9千亿+";
        }
        return finalNum;
    },
    formatFileSize:function(bytes) {
        if (parseInt(bytes) === 0) return '0B';
        var k = 1024,
        sizes = ['B','KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(bytes) / Math.log(k));
        var val = (bytes / Math.pow(k, i)).toFixed(2);
        var to_val = parseInt(val) == val?(val*1).toFixed(0):val;
        return to_val + sizes[i];
    },
    decodeRecord:function(num){
        var num1=0,num2=0,num3= 0;
        var array1 = num.split('亿'),array2 = [];
        if(array1.length>1){
            num1 = parseInt(array1[0]);
            array2 = array1[1].split('万');
        }else{
            num1 = 0;
            array2 = array1[0].split('万');
        }
        if(array2.length>1){
            num2 = parseInt(array2[0]);
            num3 = parseInt(array2[1]);
        }else{
            num2 = 0;
            num3 = parseInt(array2[0]);
        }
        return [num1,num2,num3];
    },
    /* 数据导入时间格式化 */
    exchangeTime: function (mss) {
        var days = parseInt(mss / (1000 * 60 * 60 * 24));
        var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = parseInt((mss % (1000 * 60)) / 1000);
        var str = '';
        if (days) str = str + days + "天";
        if (hours) str = str + hours + "时";
        if (minutes) str = str + minutes + "分";
        if (seconds) str = str + seconds + "秒";
        return str;
    },
    sys: function () {
        return getBrowserInfo();
    },
    rand: function (digit) {
        var n="";
        for(var i=0;i<digit;i++){
            n+=Math.floor(Math.random()*10);
        }
        return n;
    }
};
String.prototype.trim=function(){ return this.replace(/(^\s*)|(\s*$)/g, ""); };
/**
 * 扩展DATE属性，增加日期格式化方法
 * @param f
 * @returns {*}
 */
Date.prototype.format = function(f){
    var o ={
        "M+" : this.getMonth()+1, //month
        "d+" : this.getDate(),    //day
        "H+" : this.getHours(),   //hour
        "m+" : this.getMinutes(), //minute
        "s+" : this.getSeconds(), //second
        "q+" : Math.floor((this.getMonth()+3)/3),  //quarter
        "S" : this.getMilliseconds() //millisecond
    };
    if(/(y+)/.test(f))f=f.replace(RegExp.$1,(this.getFullYear()+"").substr(4 - RegExp.$1.length));
    for(var k in o)
        if(new RegExp("("+ k +")").test(f))f = f.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));return f
};
/**
 * 判断浏览器类型
 * @returns {{}}
 */
function getBrowserInfo(){
    var browserName=navigator.userAgent.toLowerCase();
    if(/msie/i.test(browserName) && !/opera/.test(browserName)){  
        return "ie";  
    }else if(/firefox/i.test(browserName)){  
        return "firefox";  
    }else if(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName)){  
        return "chrome";  
    }else if(/opera/i.test(browserName)){  
        return "opera";  
    }else if(/iPad/i){
        return "ipad"; 
    }else if(/webkit/i.test(browserName) &&!(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName))){  
        return "safari";  
    }else{  
        return"unKnow";  
    }  
}
var sys = getBrowserInfo();

/**
 * 通过分页选择获取 所需分页的信息
 * @type {{pageAct: Function, pageSize: Function, totalPage: Function}}
 */
var pageInfo={
    /**
     * 获取当前所在页 参数可选
     * @param page_selector or JQuery obj
     * @returns {*}
     */
    pageAct:function(page_selector){
        var $_select = Util.isEmpty(page_selector)?$("body"):!Util.isEmpty(page_selector.jquery)?page_selector:$(page_selector);
        var pageNum = Util.isEmpty($_select.find(".page-block.active").html())?1:parseInt($_select.find(".page-block.active").html());
        return pageNum==0?1:pageNum;
    },
    /**
     * 获取当前页面所展示条目数 参数可选
     * @param page_selector
     * @returns {*}
     */
    pageSize:function(page_selector){
        var $_select = Util.isEmpty(page_selector)?$("body"):!Util.isEmpty(page_selector.jquery)?page_selector:$(page_selector);
        var pageSize = Util.isEmpty($_select.find(".pageSize").val())?10:$_select.find(".pageSize").val();
        return (pageSize<5)?5:(pageSize>1000)?1000:pageSize;
    },
    /**
     * 获取当前页面当前状态下总页数 参数可选
     * @param page_selector
     * @returns {*}
     */
    totalPage: function(page_selector){
        var $_select = Util.isEmpty(page_selector)?$("body"):!Util.isEmpty(page_selector.jquery)?page_selector:$(page_selector);
        return Util.isEmpty($_select.find(".pageCount").html())?1:parseInt($_select.find(".pageCount").html());
    },
    /**
     * 下一页方法，传入需要分页的分页容器选择器，通过回调函数将分页信息传回
     * 若code=400则未通过下一页验证，请使用者勿执行分页函数，
     * 若code=200,则使用者可以获取page属性作为下一页参数传入分页函数
     * @param page_selector
     * @param fn
     */
    next: function (page_selector,fn) {
        var sel = $.isFunction(arguments[0])?"":arguments[0];
        var data = {},pageAct = pageInfo.pageAct(sel),totalPage = pageInfo.totalPage(sel);
        if(pageAct>=totalPage || pageAct==0){
            data.code=400;
            data.page=pageAct;
        }else{
            data.code=200;
            data.page=pageAct+1;
        }
        for(var i=0;i<arguments.length;i++){
            $.isFunction(arguments[i])?arguments[i](data):"";
        }
    },
    /**
     * 上一页方法同下一页方法
     * @param page_selector
     * @param fn
     */
    before: function (page_selector,fn) {
        var sel = $.isFunction(arguments[0])?"":arguments[0];
        var data = {},pageAct = pageInfo.pageAct(sel),totalPage = pageInfo.totalPage(sel);
        if(pageAct<=1 || totalPage<=1){
            data.code=400;
            data.page=pageAct;
        }else{
            data.code=200;
            data.page=pageAct-1;
        }
        for(var i=0;i<arguments.length;i++){
            $.isFunction(arguments[i])?arguments[i](data):"";
        }
    },
    /**
     * 跳转页数方法
     * @param page_selector
     * @param fn
     */
    jump: function(page_selector,fn){
        var sel = $.isFunction(arguments[0])?"":arguments[0];
        var data = {},pageAct = pageInfo.pageAct(sel),totalPage = pageInfo.totalPage(sel);
        var $_select = Util.isEmpty(page_selector)?$("body"):!Util.isEmpty(page_selector.jquery)?page_selector:$(page_selector);
        var jump = $_select.find(".page-con").find("input").val();
        if(Util.isEmpty(jump) || isNaN(jump) || parseInt(jump)>totalPage || parseInt(jump)<1){
            data.code=400;
            data.page=pageAct;
        }else{
            data.code=200;
            data.page=parseInt(jump);
        }
        for(var i=0;i<arguments.length;i++){
            $.isFunction(arguments[i])?arguments[i](data):"";
        }
    },
    getCookie:function(cookie_name){
        var allcookies = document.cookie;
        var cookie_pos = allcookies.indexOf(cookie_name);   //索引的长度
        // 如果找到了索引，就代表cookie存在，
        // 反之，就说明不存在。
        if (cookie_pos != -1) {
            // 把cookie_pos放在值的开始，只要给值加1即可。
            cookie_pos += cookie_name.length + 1;//这里容易出问题，所以请大家参考的时候自己好好研究一下
            var cookie_end = allcookies.indexOf(";", cookie_pos);
            if (cookie_end == -1) {
                cookie_end = allcookies.length;
            }
            var value = unescape(allcookies.substring(cookie_pos, cookie_end));//这里就可以得到你想要的cookie的值了。。。
        }
        return value;
    },
    setCookie:function(name,value){
        var Days = 30;
        var exp = new Date();
        exp.setTime(exp.getTime() + Days*24*60*60*1000);
        document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
    }
};
(function ($) {
    var dfOption ={
        maxHeight:"",
        fixedHeader:true,//是否固定表头
        type:1,//表格类型：1：普通型2：分组型
        showPage:true,//是否显示分页
        showPageNum:5,//底部分页的页码个数默认5个
        pageType:"inside",//分页类型 inside：表格内部显示分页(与表格共享纵向滚动条) out：与表格同级分页分页固定置于容器底端
        showNum:true,//是否自动显示序号列
        numType:1,//序号列类型
        rowData:[
            {key:"",attrName:""}//key:为columns里的key attrName为该tr属性名称，支持多个属性，暂无上限
        ],
        head:[
            {field:"",type:1,style:"",name:"",format:"time",sort:true,sortType:"common",rule:{},size:""}//field:字段，type：1=普通数据(将作为key直接获取数据)，2=dom数据(使用者自定义该列数据)，format:"time"/"mun"/"data"/"date"，暂时只支持格式化时间(time),(date只有如期没有具体时间)
        ],
        sort:false,
        columns:[],//以 { key : value , key : value} 形式
        pageInfo:{//分页信息
            currentPage:1,
            pageSize:1,
            totalPage:1,
            totalRecords:0
        },
        showColumns:true,
        groupName:"",//分组显示名称 当type=2时必填
        groupKey:"",//columns里所需分组字段key 当type=2时必填
        align:"center",//表格内容左对齐
        patch:false,//补白该属性在 pageType为out时起效，用于将空白处补足空白行
        done: function($table){},//表格生成后回调函数
        page: function(page){}//分页方法
    };
    var optionList={};
    $.fn.cakeTable = function (option) {
        var $_table_container = $(this);//获取承载表格的容器，亦可以是body对象
        var $_fixed_Table = $_table_container.hasClass("fixed-table")?$_table_container:$_table_container.find(".fixed-table");//通过容器获得表格dom，可以是多个，亦可以是空
        if(typeof option === "string"){//判断参数，若为字符串则认定为调用指定方法
            return pathfinder(option,$_fixed_Table);
        }
        var opt = $.extend({},dfOption,option);

        var temp = Util.template($("#cakeTable-template").html(),{option:opt,pageInfo:opt.pageInfo});
        $_table_container.empty();
        $_table_container.css("position","relative").html(temp);//给表格容器赋定位使每页显示条数正常使用
        (!Util.isEmpty(opt.maxHeight))?$_table_container.find(".fixed-table>.fixed-table-body").css("max-height",opt.maxHeight-34):"";
        if(!Util.isEmpty(opt.rowData) && !Util.isEmpty(opt.columns)){//设置tr属性
            if(opt.type==1){
                $_table_container.find("table>tbody>tr").each(function (i) {
                    var $_tr = $(this);
                    $.each(opt.rowData, function (j,n) {
                        if(!Util.isEmpty(n.key,n.attrName)){
                            $_tr.attr(n.attrName,opt.columns[i][n.key]);
                        }
                    });
                })
            }else if(opt.type==2){
                $_table_container.find(".table-group-fa").each(function (i) {
                    var $_tr_fa = $(this);
                    var groupName = $_tr_fa.attr("group");
                    $(".table-group-ch[group='"+groupName+"']").each(function (ii) {
                        var $_tr_ch = $(this);
                        $.each(opt.rowData, function (iii,n) {
                            if(!Util.isEmpty(n.key,n.attrName)){
                                $_tr_ch.attr(n.attrName,opt.columns[i][opt.groupKey][ii][n.key]);
                            }
                        });
                    })
                }).click(function () {
                    showSub(this);
                });
            }
        }

        $_table_container.find("table").delegate(".show_dt","click",function(){//已弹出框形式显示内容长度超过35字符的内容
            pop.alert($(this).attr("value"));
        });

        /***
         * 绑定自定义checkbox事件
         */
        $_table_container.find(".fixed-table").delegate(".table-property","click",function(){
            if($(this).hasClass("check-all")){
                if($(this).find(".table-checkbox").hasClass("active")){
                    $_table_container.find(".table-checkbox").removeClass("active");
                }else{
                    $_table_container.find(".table-checkbox").addClass("active");
                }
            }else{
                if($(this).find(".table-checkbox").hasClass("active")){
                    $(this).find(".table-checkbox").removeClass("active");
                    $_table_container.find(".table-property.check-all .table-checkbox").removeClass("active");
                }else{
                    $(this).find(".table-checkbox").addClass("active");
                }
            }
        });
        
        $.isFunction(opt.done)?opt.done($_table_container.find(".fixed-table")):"";//表格生成完毕时的回调函数
        (opt.type==2)?tableGroup():"";//分组表格生成

        saveOption($_table_container,opt);//保存配置
        initTableCss($_table_container.find(".fixed-table"));//初始化表格样式
        if(opt.pageType === "out" && opt.showPage){
            $_table_container.find(".fixed-table").css("height","calc(100% - 58px)");
        }

        $_table_container.find(".fixed-table-head div,.fixed-table-body table thead tr th,.fixed-table-body table tbody tr td").css("text-align",opt.align);

        //$_table_container.find("table").TableSorter(opt.showNum);//表格排序以及列隐藏\显示
        var $_page_con = $_table_container.find(".page-con");
        /* 绑定该表格分页功能 */
        $_page_con.find(".page-before").click(function () {
            pageInfo.before($_page_con,function (data) {
                if(data.code==200){ opt.page(data.page); }
            })
        });
        $_page_con.find(".page-next").click(function () {
            pageInfo.next($_page_con,function (data) {
                if(data.code==200){ opt.page(data.page); }
            })
        });
        $_page_con.find("button").click(function () {
            pageInfo.jump($_table_container,function (data) {
                if(data.code==200){ opt.page(data.page); }
            })
        });
        $_page_con.find(".page-first").click(function () {
            opt.page(1);
        });
        $_page_con.find(".page-last").click(function () {
            opt.page(opt.pageInfo.totalPage);
        });
        $_page_con.find(".page-block:not(.active)").click(function () {
            var clickPage = $(this).text();
            opt.page(clickPage);
        });
        $_page_con.find(".pageSize").change(function () {
            var newPageSize = $(this).val();
            opt.page(1);
        });
        return $_table_container.find(".fixed-table");
    };
    /* 表格每页显示条数选择 */
    $("body").delegate(".show-page-box","click",function(){
        var $change = $(".change-pagesize");
        var $table = $(this).parents(".fixed-table").length==0 ? $(this).parents(".fixed-table-foot").siblings(".fixed-table") : $(this).parents(".fixed-table");
        var $_table_foot = $(this).parents(".fixed-table-foot");
        if($change.length == 1){
            $change.remove();
        }else{
            var temp = '<div class="change-pagesize">'+
                    '<div class="change-item change-item-left change-item-top">10</div><div class="change-item change-item-top">20</div><div class="change-item change-item-top">30</div>'+
                    '<div class="change-item change-item-left">50</div><div class="change-item">100</div><div class="change-item">150</div>'+
                    '<div class="change-item change-item-left">200</div><div class="change-item">300</div><div class="change-item">400</div>'+
                    '<div class="change-item change-item-left">500</div><div class="change-item">600</div><div class="change-item">自定义</div>'+
                    '</div>',
                left = $(this).position().left,
                top = $_table_foot.position().top-112;
            $table.parent().append(temp);
            $(".change-pagesize").css({top:top,left:left});
        }
    }).delegate(".change-item","click",function(){
        var $_this = $(this);
        var $_pageCon = $_this.parent().parent().find(".page-con");
        if($_this.html() != "自定义"){
            $_pageCon.find(".show-page").html($_this.html());
            $_pageCon.find("input").val(1);
            $_pageCon.find("button").click();
        }else{
            $_this.parent().hide();
            pop.dialog({
                popList : [{
                    title:"修改显示数目",
                    popContent:"<div style='text-align: center;margin: 50px 0 30px 0;'><input onpaste='return false;' onkeyup='this.value=this.value.replace(/\D/g,10)' id='num' class='cos-form-control' type='number' style='IME-MODE: disabled;text-align: center;height:28;height: 22px;'></div>",
                }],
                onLoad:function(){
                    $("#num").val($(".show-page").html());
                }
            },function(){
                var num = $("#num").val();
                if(!Util.isEmpty(num)){
                    $_pageCon.find(".show-page").html((parseInt(num)<5)?5:num);
                    $_pageCon.find("input").val(1);
                    $_pageCon.find("button").click();
                }
            })
        }
    }).click(function(){
        //表头弹出菜单
        if($(this).find(".tableHeaderMenu").length>0){
            $(".tableHeaderMenu").hide();
            $(".tableHeaderMenu").parents(".fixed-table").find(".fixed-table-head em.menu-caret-down").remove();
        }
    });

    //方法引道者
    function pathfinder(string,$_table){
        switch (string){
            case "resize":return initTableCss($_table);break;
            case "getOption":return getTableOptions($_table);break;
        }
    }
    //保存表格配置并清除已被废弃的配置
    function saveOption($_table_container,opt){
        var sjs =  parseInt(Math.random()*10000);//给表格配置随机一个数字key
        optionList[sjs]=opt;//将该表配置丢入配置集合
        $_table_container.find(".fixed-table").attr("data-idx",sjs);//给表格标记自己配置的key
        var keyList=[];//临时新建一个key集合
        $.each(optionList, function (i, n) {//循环内存中已存入的表格配置获取Key并放入临时key集合
            keyList.push(i);
        });
        $(".fixed-table").each(function () {//循环页面上所有存在的表格获取key生成已被废弃的配置的key
            var $_table = $(this);
            $.each(keyList, function (i, n) {
                if($_table.attr("data-idx")==n){
                    keyList.splice(i,1)
                }
            });
        });
        $.each(keyList, function (i,n) {//通过key 删除已被废弃的表格配置
            delete optionList[n];
        });
    }
    //获取指定表配置信息
    function getTableOptions($_table){
        return optionList[$_table.attr("data-idx")];
    }
    //分组明细隐藏
    function tableGroup(){
        var groupTr = $("tr[group]");
        groupTr.each(function(){
            var groupValue = $(this).attr("group");
            var subDetails = $("tr[groupChild='" + groupValue + "']");
            $(this).after(subDetails);
            if(subDetails.css("display")=="none"){
                $(this).find("a.add").html("+")
            }else{
                $(this).find("a.add").html("-")
            }
        });
    }
    //点击分组行时，切换分组明细的显示/隐藏
    function showSub(clickT) {
        var groupValue = $(clickT).attr("group");
        var subDetails = $("tr[groupChild='" + groupValue + "']");
        if(subDetails.css("display")=="none"){
            subDetails.show();
            $(clickT).find("a.add").html("-")
        }else{
            subDetails.hide();
            $(clickT).find("a.add").html("+")
        }
    }
    //赋予表格样式
    function initTableCss($_table){
        var $_tables = Util.isEmpty($_table)?$(".fixed-table"):$_table;
        $_tables.each(function(){
            var $_table = $(this);
            var $_div_head = $(this).find(".fixed-table-head");//容器头
            var $_div_body = $(this).find(".fixed-table-body");//容器内容
            var $_div_foot = $(this).find(".fixed-table-foot");//容器底部

            var option = optionList[$_table.attr("data-idx")];

            /*var theme = Util.getQueryString();
            var color = theme == "light" ? "#ddd" : "#535353";
            if($_div_foot.length==0){
                $_div_body.css({"max-height":"calc(100% - 1px)","border-bottom":"1px solid "+color});
            }*/

            var $this_table = $_div_body.find("table");//实际表格table
            var $_table_head_Ftr = $this_table.find("thead>tr:first-child");//表格头 第一行
            var $_table_body_Ftr = $this_table.find("tbody>tr:first-child");//表格内容 第一行

            var tableWidth = $this_table.width();//表格宽
            var tableHeight = $this_table.height();//表格高

            if($_table_head_Ftr.length>0){//给容器固定表头赋宽度
                var allWidth = 0;
                for(var i = 0;i<$_table_head_Ftr.find("th").length;i++){//循环表格头获取单列头宽度
                    if(i != $_table_body_Ftr.find("td").length-1){
                        var $_table_th = $_table_head_Ftr.find("th:eq("+i+")");//表格头指定列
                        var $_div_th = $_div_head.children().eq(i);//div固定头指定列
                        var $table_head_th_width = sys!="firefox" ? ($_table_th.width() + 1) : $_table_th.width();
                        $_div_th.css("width",$table_head_th_width);
                        $_table_th.css("width",$table_head_th_width);
                        allWidth = allWidth+$table_head_th_width
                    }else{
                        //$_div_head.children().eq(i).css("width","calc(100% - "+allWidth+"px)");
                    }
                }
            }
            var scroll_width= 0,browser=0;
            if(sys=="firefox"){
                scroll_width=16;
            }else if(sys=="chrome"){
                scroll_width=9;
                browser=1;
            }
            var $_div_body_height = $_div_body.outerHeight();//承载表格的容器实际高度-->容器高
            var $_this_table_height = $this_table.outerHeight();//承载表格的容器需要的高度-->表格高


            $_div_body.css("min-width","100%");
            if($_this_table_height>$_div_body_height){
                $_div_head.css({"width":tableWidth-browser});
                $_div_body.css({"width":tableWidth + scroll_width});
                $_div_foot.css({"width":tableWidth + scroll_width-browser});
            }else{
                $_div_head.css({"width":tableWidth-browser});
                $_div_body.css({"width":tableWidth});
                $_div_foot.css({"width":tableWidth-2});
            }
            $_div_head.css({"display":"table"});

            if(!Util.isEmpty(option) && !Util.isEmpty(option.maxHeight)){
                $_div_body.css("max-height",$_div_body.height()-($_table.height()-option.maxHeight));
            }

            if(  option.patch ){//option.pageType == "out" &&
                var tr_height = $_table_body_Ftr.height();
                var con_height = $_div_body.height();
                var table_height = $this_table.height();
                var blankHeight = (con_height - table_height)/tr_height;
                if(blankHeight > 0 ){
                    var row = parseInt(blankHeight);
                    var tr = "",td = "";
                    var border;

                    var colNum = $this_table.find("th").length;

                    for(var iii = 0;iii<colNum;iii++){
                        td+="<td></td>";
                    }

                    for(var ii = 0;ii<row-1;ii++){
                        border = ii == row-2 ? "border-bottom: 1px solid #DDD;":"";
                        tr+="<tr class='empty-tr' style='height: "+tr_height+"px;"+border+"'>"+td+"</tr>"
                    }
                    if(!option.showPage){
                        tr = "<tr class='empty-tr' style='height: "+tr_height+"px;'>"+td+"</tr>" + tr;
                    }
                    $this_table.find("tbody").append(tr);
                }
            }
            //console.log("表格高："+tableHeight+",表格宽："+tableWidth);
        });
        return null;
    }
})(jQuery);

(function ($) {
    $("body").click(function () {
        $(".selectBox").children("ul").finish().hide();
    });
    $.fn.selectBox = function (o) {
        var $_main_select = $(this);
        var option={
            readonly:true,
            maxLength:6,
            width:150,
            height:"",
            data:[],
            attr:[],
            click: function ($a) {}
        };
        $.extend(option,o);
        /***
         * 生成dom文档
         * @param opt
         * @param attr
         * @param level
         * @returns {string}
         */
        function initSelect(opt,attr,level){
            var lev = 0;
            if(!Util.isEmpty(level)){
                lev = level+30;
            }
            var ul="<ul style='padding-left: "+lev+"px;'>";
            if(opt.length>0){
                $.each(opt, function (i, n) {
                    var attrStr="";
                    if(attr.length>0){
                        $.each(attr, function (ii, nn) {
                            if(!Util.isEmpty(nn.key) && !Util.isEmpty(nn.attrName)){
                                var val = Util.isEmpty(n[nn.key])?"":n[nn.key];
                                attrStr = attrStr + nn.attrName +"='" + val + "' ";
                            }
                        })
                    }
                    var val,title="";
                    if(n.value.length> option.maxLength){
                        val=n.value.substring(0,option.maxLength)+"...";
                        title="title='"+n.value+"'";
                    }else{
                        val=n.value;
                    }
                    if(!Util.isEmpty(n.child)){
                        ul+="<li><i class='fa fa-caret-right'></i><a "+title+" "+attrStr+" class='select-link'>"+ val+"</a>"+initSelect(n.child,attr,lev)+"</li>";
                    }else{
                        ul+="<li><a "+title+" "+attrStr+" class='select-link'>"+ val+"</a></li>";
                    }
                });
                ul+="</ul>";
            }
            return ul;
        }
        $_main_select.empty().html("<div class='selectBox'><i class='fa fa-caret-down down-icon'></i><input type='text'>"+initSelect(option.data,option.attr)+"</div>");
        $_main_select.find(".selectBox>ul").hide();
        initCss($_main_select,option);

        /***
         * 根据配置展开或收齐子集
         */
        $_main_select.find(".select-link").nextAll().hide(0,function () {
            $(this).height(0);
            $_main_select.find("li").addClass("close");
        });

        /***
         * 绑定收起、闭合动画事件
         */
        $_main_select.find(".select-link").click(function (e) {
            var $_li = $(this).parent();
            var $_li_ul = $_li.children("ul");
            $_main_select.find("input").val($_li.children("a").text());
            if($_li_ul.length<1 || $_li.hasClass("moving")){return;}
            $_li.addClass("moving");
            if($_li.hasClass("open")){
                $_li.children("ul").animate({
                    height:0
                },200, function () {
                    $_li_ul.hide();
                    $_li.children("i").removeClass("fa-caret-down").addClass("fa-caret-right");
                    $_li.removeClass("open moving").addClass("close");
                })
            }else if($_li.hasClass("close")){
                var h = $_li.children("ul").children("li").length*20;
                $_li_ul.show();
                $_li.children("ul").animate({
                    "height":h
                },200, function () {
                    $(this).css("height","");
                    $_li.children("i").removeClass("fa-caret-right").addClass("fa-caret-down");
                    $_li.removeClass("close moving").addClass("open");
                })
            }
            option.click($_li.children("a"));
            e.stopPropagation();
        });

        $(this).find(".selectBox").click(function (e) {
            $(this).children("ul").off("mouseleave mouseleave").show().css("opacity",1).mouseleave(function () {
                $(this).animate({
                    "opacity":0
                },500,function(){
                    $(this).hide();
                })
            }).mouseenter(function () {
                $(this).stop().show();
                $(this).animate({
                    "opacity":1
                },200)
            });
            e.stopPropagation();
        });

    };
    function initCss($select,option){
        $select.find(".selectBox").css({
            "width":option.width
        });
        $select.find(".selectBox>ul").css({
            "max-height":Util.isEmpty(option.height)?300:option.height
        });
        if(option.readonly){
            $select.find("input").attr({
                "readonly":"readonly"
            })
        }
    }

})(jQuery);


(function($) {
    $.fn.validator = function(option){
        

        var methods = {
            required : function(value, element){
                return $.trim(value).length > 0 && value != message[element.attr("name")];
            },
            email: function(value, element) {
                return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value);
            },
            mobilephone : function(value, element){
                return /^1[3|4|5|7|8][0-9]\d{8}$/.test(value);
            },
            phone : function(value, element){
                return /^0\d{2,3}-?\d{7,8}$/.test(value);
            },
            range : function(value, element){
                var min = element.attr("min"),
                    max = element.attr("max"),
                    digit =  element.attr("digit"),
                    isDigit = null;
                if(digit){
                    isDigit = /^\d+$/.test(value)
                }
                return Number(value)>=Number(min) && Number(value)<=Number(max) && isDigit;
            }
        };

        var message = {
            required : "必填",
            email: "请输入正确的电子邮件",
            mobilephone : "请输入正确的手机号码",
            phone : "请输入正确的电话号码",
            range : function(value, element){
                var min = $(element).attr("min"),
                    max = $(element).attr("max"),
                    digit =  $(element).attr("digit"),
                    isDigit = "数值";
                if(digit){
                    isDigit = "整数";
                }
                return "请输入"+min+"~"+max+"的"+isDigit;
            }
        };

        var $validateItem = $(this).find(".validate");
        if(option.validate){
            $validateItem.each(function(i, v){
                doValidate($(v).val(),$(v).attr("name"),$(v));
            })
        }else{
            $validateItem.bind("blur", function(){
                doValidate($(this).val(),$(this).attr("name"),$(this));
            });
            $validateItem.bind("focus", function(){
                var value = $(this).val();
                var validateType = $(this).attr("name");
                var messageValue = typeof(message[validateType]) == "function" ? message[validateType](value,$(this)) : message[validateType];
                if(messageValue == value){
                    $(this).css("border","1px solid #ddd");
                    $(this).val("");
                    $(this).removeAttr("failed");
                }
            });
        } 
        function doValidate(value, validateType,ele){
            if(methods[validateType](value,$(ele))){
                $(ele).css("border","1px solid #ddd");
                $(ele).removeAttr("failed");
            }else{
                $(ele).removeAttr("value");
                var messageValue = typeof(message[validateType]) == "function" ? message[validateType](value,$(ele)) : message[validateType];
                $(ele).css("border","1px solid #F50505");
                $(ele).val(messageValue);
                $(ele).attr("failed","failed");
            }
        }
    }
})(jQuery);

(function($) {
    $.fn.dropDownSelect = function(option){
        var $dropDownSelect = $(this);
        var $dropDownMenu = $dropDownSelect.find(".dropdown-menu");
        if(option.listData&& isArray(option.listData)){
            var menuList = "<li><a href='#' key=''>请选择</a></li>";
            $(option.listData).each(function(i, v){
                menuList = menuList + "<li><a href='#' key='"+  v[option.key] +"'>" + v[option.value] + "</a></li>"
            });
            $dropDownMenu.html(menuList);
        }
        /*$dropDownMenu.find("a").click(function(){
            var $_showVal = $dropDownSelect.find(".dropdown-toggle");
            if($_showVal[0].type=="button"){
                $_showVal.html($(this).html());
            }else if($_showVal[0].type=="text"){
                $_showVal.val($(this).html())
            }
            $dropDownSelect.find(".dropdown-toggle").html($(this).html());
            $dropDownSelect.attr("value",$(this).attr("key"));

            //本方法为新建应用定制
            $(this).parents(".btn-group").find(".btn-group>input").removeClass("error");
        });*/

        $dropDownSelect.find(".spt-top-btn").click(function(){
            var cur = $dropDownSelect.attr("value") ? $dropDownSelect.attr("value") : "";
            if(Util.isEmpty(cur)){

            }
            var prev = $dropDownMenu.find("a[key="+cur+"]").parent().prev().find("a");

            //$dropDownSelect.find(".dropdown-toggle").html(prev.html());
            var $_showVal = $dropDownSelect.find(".dropdown-toggle");
            if($_showVal[0].type=="button"){
                $_showVal.html(prev.html());
            }else if($_showVal[0].type=="text"){
                $_showVal.val(prev.html())
            }

            $dropDownSelect.attr("value",prev.attr("key"));
        });

        $dropDownSelect.find(".spt-bottom-btn").click(function(){
            var cur = $dropDownSelect.attr("value") ? $dropDownSelect.attr("value") : "";
            var next = $dropDownMenu.find("a[key="+cur+"]").parent().next().find("a");

            //$dropDownSelect.find(".dropdown-toggle").html(next.html());
            var $_showVal = $dropDownSelect.find(".dropdown-toggle");
            if($_showVal[0].type=="button"){
                $_showVal.html(next.html());
            }else if($_showVal[0].type=="text"){
                $_showVal.val(next.html())
            }

            $dropDownSelect.attr("value",next.attr("key"));
        });

        function isArray(obj) {   
            return Object.prototype.toString.call(obj) === '[object Array]';    
        }  
    }
})(jQuery);

$("body").delegate(".property","click",function(){
    if(!$(this).hasClass("disabled")){
        var name = $(this).attr("name");
        var $_checkBox = $(this).find(".user-check");
        if($_checkBox.hasClass("checked")){
            $_checkBox.removeClass("checked");
            if(!Util.isEmpty(name)){
                $(".property-all[name='"+name+"']").find(".user-check").removeClass("checked");
            }else{
                $(".property-all").find(".user-check").removeClass("checked");
            }
        }else{
            $_checkBox.addClass("checked");
            var brothers = $(".property[name="+name+"]").find(".user-check").length;
            var checkBrothers = $(".property[name="+name+"]").find(".checked").length;
            if(brothers == checkBrothers){
                if(!Util.isEmpty(name)){
                    $(".property-all[name='"+name+"']").find(".user-check").addClass("checked");
                }else{
                    $(".property-all").find(".user-check").addClass("checked");
                }
            }
        }
    }
}).delegate(".property-all","click",function(){
    if(!$(this).hasClass("disabled")){
        var name = $(this).attr("name");
        var $_allBtn = $(this).find(".user-check");
        var $_checkBox = Util.isEmpty(name)?$(".user-check"):$(".property[name='"+name+"']").find(".user-check");
        if($_allBtn.hasClass("checked")){
            $_allBtn.removeClass("checked");
            $_checkBox.removeClass("checked");
        }else{
            $_allBtn.addClass("checked");
            $_checkBox.addClass("checked");
        }
    }
}).delegate(".btn-group[role='group'] .dropdown-menu a","click",function(){
    var $showDataDom = $(this).parents(".dropdown-menu").prev(".dropdown-toggle");
    var _showData = $(this).text();
    var _value = $(this).attr("data-val");
    var type = $showDataDom[0].type;
    if(type=="button"){
        $showDataDom.html(_showData).attr("data-val",_value);
    }else if(type=="text"){
        $showDataDom.val(_showData).attr("data-val",_value);
    }
}).delegate("input[data-verification='empty'],select[data-verification='empty']","blur",function(){
    if(Util.isEmpty($(this).val())){
        $(this).addClass("error");
    }else{
        $(this).removeClass("error");
    }
});
